import Vue from 'vue';

Vue.directive('dialogdrag', {
    bind(el, binding, vnode, oldVnode) {

        if (binding.value === false) {
            return;
        }

        // 获取拖拽内容头部
        const $header = el.querySelector('.el-dialog__header');

        $header.style.cursor = 'move';
        const $dialog = el.querySelector('.el-dialog');
        let moveNode;
        let mouseMove = (event) => {
            event.preventDefault();
            event.stopPropagation();
            if (!moveNode) {
                mouseUp(event);
                return;
            }
            let isIE9 =
                navigator.appName == "Microsoft Internet Explorer" &&
                parseInt(
                    navigator.appVersion
                        .split(";")[1]
                        .replace(/[ ]/g, "")
                        .replace("MSIE", "")
                ) == 9;
            if (!isIE9 && event.buttons != 1) {
                // 鼠标左键没有按住
                mouseUp(event);
                return;
            }

            let endX = event.clientX;
            let endY = event.clientY;
            let distanceX = endX - moveNode.startX;
            let distanceY = endY - moveNode.startY;

            let top = new Number(moveNode.startTop) + distanceY;
            let left = new Number(moveNode.startLeft) + distanceX;
            if (top < 0) {
                top = 0;
            } else if (top > moveNode.maxTop) {
                top = moveNode.maxTop;
            }

            if (left < 0) {
                left = 0;
            } else if (left > moveNode.maxLeft) {
                left = moveNode.maxLeft
            }

            $dialog.style.margin = `${top}px 0px 0px ${left}px`;


        };
        let mouseUp = (event) => {
            document.removeEventListener('mousemove', mouseMove);
            document.removeEventListener('mouseup', mouseUp);
            moveNode = null;
        }
        $header.addEventListener('mousedown', (event) => {
            if (event.buttons !== 1) {
                // 不是鼠标左右按下的则不执行下一步操作

                return;
            }
            console.log($dialog.clientHeight, $dialog.clientWidth, document.documentElement.clientWidth, document.documentElement.clientHeight)
            moveNode = {
                startX: event.clientX,
                startY: event.clientY,
                startLeft: parseFloat($dialog.offsetLeft),
                startTop: parseFloat($dialog.offsetTop),
                maxTop: document.documentElement.clientHeight - $dialog.clientHeight,
                maxLeft: document.documentElement.clientWidth - $dialog.clientWidth

            }

            document.addEventListener('mousemove', mouseMove)


        });



    }
});